package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    static String ip = "127.0.0.1";
    static int port = 3306;
    static String database = "hutubill";
    static String encoding = "UTF-8";
    static String loginName = "root";
    static String password = "admin";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException{
        String url = String.format("jdbc:mysql://%s:%d/%s?characterEncodeing=%s&serverTimezone=GMT",ip,port,database,encoding);
       // String url = "jdbc:mysql://localhost:3306/hutubill?useSSL=false&serverTimezone=UTC&characterEncoding=UTF8";
        return DriverManager.getConnection(url,loginName,password);
    }

    public static void truncate(String table) {

        //String t = table;

        String sql1 = "SET FOREIGN_KEY_CHECKS=0";
        String sql2 = "SET FOREIGN_KEY_CHECKS=1";
        String sql = "TRUNCATE TABLE "+table;
        try(Connection c = DBUtil.getConnection();
            Statement s = c.createStatement()) {

            s.execute(sql1);
            s.execute(sql);
            s.execute(sql2);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
